package com.ios.common.action;

import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.xwork.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.XmlWebApplicationContext;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.Preparable;

public abstract class CommonAction extends ActionSupport implements ServletRequestAware, ServletResponseAware, Preparable /** SessionAware,* */
{

	private static final long serialVersionUID = 1L;
	protected HttpServletResponse response;
	protected HttpServletRequest request;
	protected WebApplicationContext context;

	// 字典缓存
	@SuppressWarnings("unchecked")
	protected Map<String, List> dicMap;

	public CommonAction() {
		super();
	}

	public void setServletRequest(HttpServletRequest httpservletrequest) {
		this.request = httpservletrequest;
	}

	public void setServletResponse(HttpServletResponse httpservletresponse) {
		this.response = httpservletresponse;
	}

	/**
	 * 页面提示信息
	 * 
	 * @param msg
	 */
	public void alert(String msg) {
		response.setContentType("text/html; charset=utf-8");
		String message = (String)request.getAttribute("alertMessage");
		if (StringUtils.isEmpty(message)) {
			message = msg;
		}
		request.setAttribute("alertMessage", message);
	}

	@SuppressWarnings("unchecked")
	public void prepare() throws Exception {
		ServletContext servletContext = ServletActionContext.getServletContext();
		Object o = servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
		if (!(o instanceof XmlWebApplicationContext)) {
			servletContext.removeAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
			new ContextLoader().initWebApplicationContext(servletContext);
			o = (WebApplicationContext)servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
		}
		this.context = (WebApplicationContext)o;
		// 获取字典
		dicMap = (Map<String, List>)this.request.getSession().getServletContext().getAttribute("DIC");
	}

	public HttpServletResponse getResponse() {
		return response;
	}

	public void setResponse(HttpServletResponse response) {
		this.response = response;
	}

	public HttpServletRequest getRequest() {
		return request;
	}

	public void setRequest(HttpServletRequest request) {
		this.request = request;
	}

	public WebApplicationContext getContext() {
		return context;
	}

	public void setContext(WebApplicationContext context) {
		this.context = context;
	}
}
